package com.gimc.evil.service

import org.slf4j.{Logger, LoggerFactory}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.connection.RedisConnection
import org.springframework.data.redis.core.{RedisCallback, RedisTemplate, ScanOptions}
import org.springframework.data.redis.serializer.RedisSerializer
import org.springframework.stereotype.Service

/**
 *
 * @author yin.he
 */
@Service
class RedisDelMatchService {

  private[this] val LOGGER: Logger = LoggerFactory.getLogger(getClass)

  @Autowired
  private[this] val redisTemplate: RedisTemplate[String, Object] = null

  def delPrefixKey(prefixKey: String): Boolean = {
    val start = System.currentTimeMillis()
    val redisCallback: RedisCallback[Long] = new RedisCallback[Long] {
      override def doInRedis(redisConnection: RedisConnection): Long = {
        val scanOptionsBuilder = ScanOptions.scanOptions()
        scanOptionsBuilder.`match`(prefixKey + "*")
        val scanOptions = scanOptionsBuilder.build()
        val cursor = redisConnection.scan(scanOptions)
        var count = 0
        while (cursor.hasNext) {
          count += 1
          val key: String = RedisSerializer.string().deserialize(cursor.next())
          redisConnection.del(RedisSerializer.string().serialize(key))
          LOGGER.info(s"删除第${count}个key $key")
        }
        count
      }
    }
    val count: Long = redisTemplate.execute(redisCallback)
    val consume = System.currentTimeMillis() - start
    LOGGER.info(s"总共消耗时间 $consume 毫秒 共删除key个数： $count")
    true
  }

  def prefixList(prefixKey: String): Set[String] = {
    val start = System.currentTimeMillis()
    val redisCallback: RedisCallback[Set[String]] = new RedisCallback[Set[String]] {
      override def doInRedis(redisConnection: RedisConnection): Set[String] = {
        var keySet: Set[String] = Set()
        val scanOptionsBuilder = ScanOptions.scanOptions()
        scanOptionsBuilder.`match`(prefixKey + "*")
        val scanOptions = scanOptionsBuilder.build()
        val cursor = redisConnection.scan(scanOptions)
        while (cursor.hasNext) {
          val key: String = RedisSerializer.string().deserialize(cursor.next())
          LOGGER.info(s" key >>> $key")
          keySet += key
        }
        keySet
      }
    }
    val result: Set[String] = redisTemplate.execute(redisCallback)
    val consume = System.currentTimeMillis() - start
    LOGGER.info(s"总共消耗时间 $consume 毫秒")
    result
  }

  def delKey(key: String): Boolean = {
    redisTemplate.delete(key)
  }

}
